package com.buiminhthang.food.net;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import com.buiminhthang.food.utils.Constant;



public class HttpHelper {

	private static final int CONNECT_TIMEOUT = 30000;
	private static final String usr = "";
	private static final String pwd = "";
	private static final String urlPreFix = Constant.HOST;

	public static JSONObject HOLDER;

	public static HttpResult makeRequest(String path, ArrayList<NameValuePair> params) {
		String vRet = null;
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(urlPreFix + path);
		HttpResponse response = null;
		try {
			URL url = new URL(urlPreFix + path);
			httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),new UsernamePasswordCredentials(usr, pwd));
			if (params != null) httpost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			response = httpclient.execute(httpost);
			if (response != null) {
				int responeCode = (response.getStatusLine()!=null)?(response.getStatusLine().getStatusCode()):1000;
				if (responeCode == HttpURLConnection.HTTP_OK) {
					InputStream recieved_information = response.getEntity().getContent();
					vRet = convertStreamToString(recieved_information);
				} else {
					return null;
				}
			} else {
				return null;
			}
		} catch (Exception ex) {
			return null;
		}
		return HttpResult.fromJson(vRet);
	}

	private static String convertStreamToString(InputStream stream) {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		String line = null;
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (Exception e) {
			return null;
		}
		return sb.toString();

	}



}